import { ViewEncapsulation } from '@angular/compiler/src/core';
import {
  Component,
  ViewChild,
  ComponentFactoryResolver,
  ViewContainerRef,
  QueryList,
  TemplateRef,
  ViewChildren,
  OnInit,
  AfterContentInit
} from '@angular/core';
import {
  ControlWidget,
  toBool,
  SFObjectWidgetRenderType,
  ArrayProperty,
  SFGridSchema,
  ObjectWidget,
  ObjectLayoutWidget,
  FormProperty
} from '@delon/form';
import type { NzSafeAny } from 'ng-zorro-antd/core/types';

import { TabsetItemWidget } from '../tabset-item/tabset-item.widget';

@Component({
  selector: 'my-object',
  templateUrl: './object-tabset.widget.html'
})
export class ObjectTabsetWidget extends ObjectLayoutWidget implements OnInit, AfterContentInit {
  static readonly KEY = 'objectTabset';

  @ViewChildren('tabsetItem')
  tabsetItems!: QueryList<TemplateRef<any>>;
  @ViewChild('tabsetItem')
  tabsetItem!: QueryList<TemplateRef<any>>;

  grid: NzSafeAny;
  type: SFObjectWidgetRenderType = 'default';
  list: NzSafeAny[] = [];
  tabList: NzSafeAny[] = [];
  title: string | undefined;
  showExpand = true;
  expand = true;

  tabs = [1, 2, 3];

  ngOnInit(): void {
    const { formProperty, ui } = this;
    const { grid, showTitle, type } = ui;
    this.showExpand = toBool(ui.showExpand, true);
    this.expand = toBool(ui.expand, true);
    this.type = type ?? 'default';
    if (this.type === 'card' || (!formProperty.isRoot() && !(formProperty.parent instanceof ArrayProperty) && showTitle === true)) {
      this.title = this.schema.title as string;
    }
    this.grid = grid as SFGridSchema;
    const list: NzSafeAny[] = [];
    const tabList: NzSafeAny[] = [];
    for (const key of formProperty.propertiesId) {
      const property = (formProperty.properties as { [key: string]: FormProperty })[key] as FormProperty;
      const item = {
        property,
        grid: property.ui.grid || grid || {},
        spanLabelFixed: property.ui.spanLabelFixed,
        show: property.ui.hidden === false
      };
      if (property.ui.widget === 'tabsetItem') {
        tabList.push(item);
      } else {
        list.push(item);
      }
    }
    this.tabList = tabList;
    this.list = list;
  }

  changeExpand(): void {
    if (!this.showExpand) {
      return;
    }
    this.expand = !this.expand;
    this.detectChanges(true);
  }
  ngAfterContentInit(): void {
    console.log(this.tabsetItems);
  }
}
